package middleware

import (
	"fmt"

	"github.com/gin-gonic/gin"
)

type UserError struct {
	Code int    `json:"code"`
	Msg  string `json:"msg"`
}

// 错误处理
func ErrorHandler() gin.HandlerFunc {
	return func(c *gin.Context) {
		defer func() {
			if err := recover(); err != nil {
				// 终止后续处理链
				c.Abort()
				if slice, ok := err.([]any); ok {
					code, msg := respondWithErrorSafe(slice)
					c.JSON(200, gin.H{
						"code": code,
						"msg":  msg,
					})

					return
				}

				e, ok := err.(error)
				if !ok {
					e = fmt.Errorf("%v", err)
				}
				c.JSON(500, gin.H{
					"code": 500,
					"msg":  e.Error(),
				})
			}
		}()
		c.Next()
	}
}

func respondWithErrorSafe(errSlice []any) (int, string) {
	// 默认值
	code := 7000
	msg := "请求被拒绝"

	c1, ok := errSlice[0].(int)
	if ok {
		code = c1
	} else {
		msg = fmt.Sprintf("%v", errSlice[0])
	}

	if len(errSlice) > 1 {
		c2, ok := errSlice[1].(string)
		if ok {
			msg = c2
		}
	}
	return code, msg
}

// 允许跨域
func CrossOrigin() gin.HandlerFunc {
	return func(c *gin.Context) {
		c.Header("Access-Control-Allow-Origin", "*") // 允许跨域
		c.Next()
	}
}
